package org.zookeeper.study;

import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;

/** 
* @author James
* @date 2018年8月16日 
*/
public class ZKOperate {
	MyZookeeper myZookeeper=new MyZookeeper();
	
	public boolean createZNode(String path,String data) {
		try {
			String zkPath=MyZookeeper.zookeeper.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
			System.out.println("ZooKeeper创建节点成功，节点地址："+zkPath);
			return true;
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public boolean deleteZNode(String path) {
		try {
			MyZookeeper.zookeeper.delete(path, -1);
			System.out.println("ZooKeeper删除节点成功，节点地址："+path);
			return true;
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (KeeperException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public boolean updateZNodeData(String path,String data) {
		try {
			Stat stat=MyZookeeper.zookeeper.setData(path, data.getBytes(), -1);
			System.out.println("更新数据成功，path："+path+",stat:"+stat);
			return true;
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public String readData(String path) {
		String data=null;
		try {
			data=new String(MyZookeeper.zookeeper.getData(path, false, null));
			System.out.println("读数据成功，path："+path+",content："+data);
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return data;
	}
	
	public List<String> getChild(String path) {
		try {
			List<String> list=MyZookeeper.zookeeper.getChildren(path, false);
			if(list.isEmpty()) {
				System.out.println("其中没有节点："+path);
			}
			return list;
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return null;
	}	
	
	public boolean isExists(String path) {
		try {
			Stat stat=MyZookeeper.zookeeper.exists(path, false);
			return stat!=null;
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	
	
}
